﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EWechatNotice
{
    public class WechatToken
    {
        public static WechatToken _WechatToken;
        public string access_token { get; set; }
        public int expires_in { get; set; }
        private DateTime createTokenTime = DateTime.Now;
        public DateTime TookenOverdueTime
        {
            get { return createTokenTime.AddSeconds(expires_in - 60); }
        }

        public static void Renovate()
        {
           
            if (_WechatToken == null)
            {
                GetNewToken();
            }

            WechatToken._WechatToken.createTokenTime = DateTime.Now;
        }

        public static bool IsTimeOut()
        {
            if (_WechatToken == null)
            {
                GetNewToken();
            }

            return WechatToken._WechatToken == null ? false : (DateTime.Now >= WechatToken._WechatToken.TookenOverdueTime);
        }
        public static WechatToken GetNewToken()
        {
            string struex = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={0}&corpsecret={1}";

            string corpID = PublicParam.CorpId; //企业ID
            string Secret = PublicParam.CorpSecret;//管理员组ID

            HttpHelper http = new HttpHelper();

            string respone = http.Get(string.Format(struex, corpID, Secret), Encoding.UTF8);

            var token = respone.ToObject<WechatToken>();

            WechatToken._WechatToken = token;

            return token;
        }

        public static string GetToken()
        {
            if (_WechatToken == null)
            {
                GetNewToken();
            }
            return _WechatToken == null ? "" : _WechatToken.access_token;
        }
    }

}
